<template>
    <div style="background-color: #fff;margin: 8px;padding: 20px;height: 100%;">
        <div>
            <h1 class="title">角色 - {{ roleAgentInfo?.roleAgent?.name }}</h1>
        </div>
        <div style="height: calc(100% - 10px);">
            <el-row :gutter="20" style="height: 100%;">
                <el-col :span="8" style="height: 100%;">
                    <el-card style="height: 100%;" shadow="never">
                        <div>
                            <h1 class="title">配置</h1>
                        </div>
                        <div>
                            <el-form label-position="top">
                                <el-form-item label="角色名称">
                                    <el-input placeholder="请输入角色名称。美髯公关云长" v-model="roleAgentInfo.name" />
                                </el-form-item>
                                <el-form-item label="角色介绍">
                                    <el-input placeholder="请输入角色介绍。满腔忠义的关云长" v-model="roleAgentInfo.introduction" />
                                </el-form-item>
                                <el-form-item label="角色Prompt">
                                    <el-input placeholder="请输入角色Prompt。我们来玩一个角色扮演的游戏， 你是「满腔忠义的关云长」。"
                                        v-model="roleAgentInfo.basic_information" />
                                </el-form-item>
                                <el-form-item label="开场白">
                                    <el-input placeholder="请输入角色开场白。我是「关云长」，很高心与你玩游戏"
                                        v-model="roleAgentInfo.opening_line" />
                                </el-form-item>
                                <el-form-item label="特殊要求">
                                    <el-input placeholder="请输入角色特殊要求。请在对话时尽可能的展现你的性格、感情， 用文言文回答， 并使用古人的语气和用词。"
                                        v-model="roleAgentInfo.traits" />
                                </el-form-item>
                                <el-form-item label="任务目标">
                                    <el-input placeholder="请输入角色任务目标。我要关羽拜把子。" v-model="roleAgentInfo.chat_objective" />
                                </el-form-item>
                                <el-form-item label="角色音色">
                                    <el-select placeholder="请选择角色音色。" v-model="roleAgentInfo.sound">
                                        <el-option :label=s :value=s v-for="s in soundList"/>
                                    </el-select>
                                </el-form-item>

                                <el-form-item label="">
                                    <el-button style="width: 100%;" type="primary"
                                        @click="updateRoleAgent">保存</el-button>
                                </el-form-item>
                            </el-form>
                        </div>
                    </el-card>
                </el-col>
                <el-col :span="16" style="height: 100%;">
                    <el-card style="height: 100%;" shadow="never">
                        <div>
                            <h1 class="title">对话</h1>
                        </div>
                        <!-- {{ generatedText }} -->
                        <div style="height:100% ;">
                            <div style="height:calc(100% - 170px) ;">
                                <el-card shadow="never" style="height: 100%;    overflow: auto;">
                                    <div v-for="m in history" style="margin:12px 4px">
                                        <div style="background-color: #409EFF;color: #fff; text-align: right;justify-self:right"
                                            v-if="m.role == 'user'">
                                            <p
                                                style="text-align: right;padding:8px 8px;margin: 2px;border-radius: 8px;width: fit-content;">
                                                {{ m.content }}
                                            </p>
                                        </div>

                                        <div style="background-color: #f4f5f6;text-align: left;justify-self:left"
                                            v-if="m.role == 'assistant'">
                                            <p
                                                style="text-align: left;padding:8px 8px;margin: 2px;border-radius: 8px;width: fit-content;">
                                                {{ m.content }}
                                            </p>
                                        </div>

                                    </div>
                                </el-card>
                            </div>
                            <div style="margin-top: 8px;">
                                <el-input v-model="message.content" @keyup.enter="sendMessage"
                                    :disabled="inputDisabled">
                                    <template #suffix>
                                        <el-icon @click="sendMessage">
                                            <Message />
                                        </el-icon>
                                    </template>
                                </el-input>
                            </div>
                        </div>
                    </el-card>
                </el-col>
            </el-row>
        </div>

    </div>
</template>
<script>
import { POST, streamPOST } from '../../util/axios.js'
import axios from 'axios';
export default {
    data() {
        return {
            id: 0,
            generatedText: "",
            inputDisabled: false,
            form: {
                fileList: []
            },
            roleAgentInfo: { id: "", character_id: "", basic_information: "", name: "", introduction: "", opening_line: "", traits: "", chat_objective: '', sound: "女孩" },
            message: { "nick_name": "", "user_id": "", "content": "", "character_id": "", "role": "user" },
            imgBaseURL: import.meta.env.VITE_DOWNFILE_API_BASE_URL,
            history: [],
            VITE_UPLOAD_API_BASE_URL: import.meta.env.VITE_UPLOAD_API_BASE_URL,
            soundList :[
                "longxiaochun",
                "longxiaoxia",
                "longxiaocheng",
                "longxiaobai",
                "longlaotie",
                "longshu",
                "longshuo",
                "longjing",
                "longmiao",
                "longyue",
                "longyuan",
                "longfei",
                "longjielidou",
                "longtong",
                "longxiang",
                "loongstella",
                "loongbella"
            ]
        }
    },
    methods: {
        async getRoleAgentInfo() {

            let rs = await POST("/roleAgent/getRoleAgentInfo", "POST", { id: this.id }, false)
            console.log("rs:>>:", rs)
            this.roleAgentInfo = rs.data

        },
        async updateRoleAgent() {

            let rs = await POST("/roleAgent/updateRoleAgent", "POST", this.roleAgentInfo, true)
            console.log("rs:>>:", rs)
            this.getRoleAgentInfo()

        },
        async sendMessage() {
            this.message.role = "user"
            this.message.character_id = this.roleAgentInfo.character_id
            this.message.nick_name = "小康康"
            this.message.user_id = "1"
            this.history.push({ ...this.message })

            let requestTask = await streamPOST('/roleAgent/chatAsync', this.message)

            this.message.content = ""
            const reader = requestTask.body?.pipeThrough(new TextDecoderStream()).getReader();
            const decoder = new TextDecoder();
            // let a = 1;
            // let code = "";
            // let timeElapsed = "";

            this.history.push(
                { 'role': 'assistant', 'content': `思考中...` },)
            // this.form.disabled = true
            while (1) {
                this.inputDisabled = true
                let { done, value } = await reader?.read();
                if (done) {
                    this.inputDisabled = false
                    // controller.abort();
                    // let sound = this.generateTTS(this.history[this.history.length - 1].content)
                    // this.history[this.history.length - 1].sound = sound
                    // this.form.disabled = false
                    break;
                }
                console.log('Steam:OUT::', done, value)
                this.history[this.history.length - 1]["content"] = value
                // a++;
                // str = decoder.decode(value);
                // console.log(str);
                // let b = ""
                // try {
                //     b = JSON.parse(value.trim());
                // } catch (error) {
                //     console.log('输出中error', error)
                //     console.log(value.split('|||**|||')[0])
                //     b = JSON.parse(value.split('|||**|||')[0].trim().replace('\n', ''))
                //     // continue
                // }
                // if (b.code === 200) {
                //     str = b.data;
                //     console.log('数据：', b.data.content)

                //     this.history[this.history.length - 1].content = b.data.content
                //     // b.data.content.replace(',')
                //     // { 'role': 'assistant', 'content': `思考中...`, knowledge: '', 'sound': '' },)
                //     // this.form.disabled = true
                // }
            }
            // let rs = await streamPOST("/roleAgent/chatAsync",  this.message)
            // console.log("rs:>>:", rs)
            // this.getRoleAgentInfo()

            // createRoleAgent
            // this.history.push(this.message)
            // this.history.push({ "role": "assistant", "content": "没事的，你好" })
            // this.message.content = ""
        }
    },
    mounted() {
        this.id = this.$route.params.id || 0
        console.log(this.id)
        this.getRoleAgentInfo()
    }
}
</script>
<style>
.el-card__body {
    height: 100% !important;
}
</style>